package com.fy56.platform.logistics.restful.api.controller.wx;


import com.alibaba.fastjson.JSON;
import com.fy56.platform.logistics.common.ResultModel;
import com.fy56.platform.logistics.common.ResultStatus;
import com.fy56.platform.logistics.model.MiniProgram;
import com.fy56.platform.logistics.model.Vip;
import com.fy56.platform.logistics.model.VipOpenidRelate;
import com.fy56.platform.logistics.restful.api.app.authorization.annotation.Authorization;
import com.fy56.platform.logistics.restful.api.utils.WeChatFormIdUtil;
import com.fy56.platform.logistics.restful.api.utils.WeChatServiceNoticeUtil;
import com.fy56.platform.logistics.service.common.ISendmsgService;
import com.fy56.platform.logistics.service.web.IMiniProgramService;
import com.fy56.platform.logistics.service.wx.IVipService;
import com.fy56.platform.logistics.utils.StringUtil;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * 推送信息RestController
 * Created by li on 2018-01-29.
 */
@Api(value = "SendMsgManager", description = "推送货物跟踪信息", produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequestMapping("/message")
public class SendMsgController {

    private static Logger log = Logger.getLogger(SendMsgController.class);

	@Autowired
	private ISendmsgService iSendmsgService;
    @Autowired
    private IMiniProgramService iMiniProgramService;
    @Autowired
    private IVipService vipService;

    @RequestMapping(value = "/send", method = RequestMethod.POST)
    @ApiOperation(value = "推送货物跟踪信息")
    @Authorization
    public ResponseEntity send(@RequestParam String data) {
        Map<String,Object> map = JSON.parseObject(data);
        try {
            return new ResponseEntity(ResultModel.ok(iSendmsgService.send(map)), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "推送货物跟踪信息"), HttpStatus.OK);
        } finally {
            map = null;
        }
    }


    /***
     * 推送微信小程序 服务通知
     */
    @RequestMapping(value = "/sendWeChatServiceNotice", method = RequestMethod.POST)
    @ApiOperation(value = "微信小程序推送货物跟踪信息")
    @Authorization
    public ResponseEntity sendWeChatServiceNotice(@RequestParam String data) {
        log.info("微信小程序推送货物跟踪信息 请求参数:  " + data );
        ResponseEntity resultEntity = null;
        // 获取微信服务通知工具类
        WeChatServiceNoticeUtil weChatServiceNoticeUtil = WeChatServiceNoticeUtil.getInstance();
        try {
            Map<String,Object> map = JSON.parseObject(data);
            // 获取小程序APP信息, 获取用户信息及formId 获取推送通知参数。
            MiniProgram miniProgram = iMiniProgramService.selectByAppId("" + map.get("appId"));
            Vip userVip = vipService.selectVipOpenidByMobile(map.get("phone")+"");

            if(miniProgram != null) {
                // 获取小程序AccessToken信息
                Map<String, Object> tokenMap = JSON.parseObject(weChatServiceNoticeUtil.getWeChatAccessToken(miniProgram.getAppid(), miniProgram.getSecret()));
                String accessToken = (tokenMap != null && !tokenMap.isEmpty()) ? tokenMap.get("access_token").toString() : "";

                if(userVip != null){

                    VipOpenidRelate searchModel = new VipOpenidRelate();
                    searchModel.setUseFlag("0");
                    searchModel.setVipMemberId(userVip.getId());
                    searchModel.setAppid(map.get("appId").toString());
                    List<VipOpenidRelate> vor = vipService.selectVipOpenidRelate(searchModel);

                    if (vor!=null && vor.size()>0){
                        VipOpenidRelate v =  vor.get(0);
                        String touser = v.getOpenid();
                        String formId = v.getFormid();

                        log.info("=====================推送微信小程序 服务通知 ========================");
                        log.info("openId: " + touser + "  formId: " + formId );
                        // 判断openId  与 fromId 不为空
                        if(StringUtil.isNotEmpty(touser) && StringUtil.isNotEmpty(formId)) {
                            // 开始推送通知
                            String[] arrayKeywords = new String[]{ map.get("ph") + "",
                                    map.get("wlcompany") + "",
                                    map.get("currentTime") + "",
                                    map.get("hwmcs") + "",
                                    map.get("jss") + "",
                                    map.get("kfzx") + "",
                                    map.get("xhdd") + ""};
                            String templateMesParam = weChatServiceNoticeUtil.getTemplateMessageJson(touser, miniProgram.getNoticeTemplateId(), formId, "/pages/index/index", arrayKeywords);
                            String result = weChatServiceNoticeUtil.sendServiceNotice(accessToken, touser, miniProgram.getNoticeTemplateId(), formId, "/pages/index/index", arrayKeywords);


                            // 更新用户formId的状态,用过的FormId失效
                            v.setUseFlag("1");
                            vipService.updateVipOpenidRelate(v);

                            // 调用结果转换为Object
                            resultEntity = new ResponseEntity(ResultModel.ok(result), HttpStatus.OK);

                            log.info("SendWeChatServiceNotice: templateMsgParams " + templateMesParam);
                            log.info("SendWeChatServiceNotice: result " + result + " 结果解析信息：" + weChatServiceNoticeUtil.getJSONResultAnalysis(result));
                        }else{
                            resultEntity =  new ResponseEntity(ResultModel.ok("用户小程序端信息错误，无相关信息" + "OPENID: "+ touser +" FORMID: " + formId ), HttpStatus.OK);
                            log.error("SendWeChatServiceNotice: 用户小程序端信息错误，无相关信息" + "OPENID: "+ touser +" FORMID: " + formId );
                        }

                    } else {
                        resultEntity =  new ResponseEntity(ResultModel.ok("用户小程序端信息错误，无可用formid"), HttpStatus.OK);
                        log.info("SendWeChatServiceNotice: 用户小程序端信息错误，无可用formid" );
                    }

                }else{
                    // 判断 phone 对应用户信息是否正确存在
                    resultEntity =  new ResponseEntity(ResultModel.ok(data + "，phone用户不存在。"), HttpStatus.OK);
                    log.error("SendWeChatServiceNotice: " + data + "，phone用户不存在。");
                }
            }else{
                // 判断 appId 对应小程序信息是否正确存在
                resultEntity =  new ResponseEntity(ResultModel.ok(data + "，数据中AppId参数不正确,未获取到小程序相关配置信息。"), HttpStatus.OK);
                log.error("SendWeChatServiceNotice: " + data + "，数据中AppId参数不正确,未获取到小程序相关配置信息。。");
            }
        } catch (Exception ex) {
            resultEntity = new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "小程序推送货物跟踪信息" + ex.getMessage()), HttpStatus.OK);
            log.error("微信小程序推送货物跟踪服务通知信息，Exception：" , ex);
        }
        return resultEntity;
    }


}